#include "ObjReader.h"

Mesh *
ObjReader::readFile (const char * path)
{
	Mesh *mesh = new Mesh();
	if(path == NULL)
		return mesh;
	
	std::ifstream file;
	
	file.open(path);
	
	
	if (!file.good()) {
		file.close();
		return mesh;
	}
	
	std::string array[4];
	
	while (!file.eof())
	{
		char line[1024];
		if (file.eof())
			break;
		array[0] = "";
		file.getline(line,1024);
		std::string data(line);
		split(2, ' ', data, array);
		std::string prefix = array[0];
		if (!prefix.compare("v")) {
			split(4,' ', data, array);
			Point3d p(atof(array[1].c_str()), atof(array[2].c_str()), atof(array[3].c_str()));
			mesh->addVertex(p);
		}
		else if (!prefix.compare("vt")) {
			split(3, ' ', data, array);
			Point2d p(atof(array[1].c_str()), atof(array[2].c_str()));
			mesh->addTexture(p);
		}
		else if (!prefix.compare("vn")) {
			split(4, ' ', data, array);
			Point3d p(atof(array[1].c_str()), atof(array[2].c_str()), atof(array[3].c_str()));
			mesh->addNormal(p);
		}
		else if (!prefix.compare("f")) {
			split(4, ' ', data, array);
			Face f;
			FacePoint f1 = splitFace('/',array[1]);
			FacePoint f2 = splitFace('/',array[2]);
			FacePoint f3 = splitFace('/',array[3]);
			f.addPoint(f1);
			f.addPoint(f2);
			f.addPoint(f3);
			mesh->addFace(f);
		}
					
	}
	file.close();
	return mesh;	
}